- Recursion

1) Recursive method:

A method calling itself. 

a) Base case: method can handle in this case the input
b) Recursive step: this is where the method calls itself

Example#1: Sum App

main <--0--> sumRec(0): n = 0 

main <--1---> SumRec(1): n = 1 : return 1 + sumRec(0) <--0---> sumRec(0): n = 0


 private static long sumRec(int n) {
        if (n == 0)
            return 0L;
        return n + sumRec(n - 1);
    }

Recursive solution: time complexity: O(n) and space complexity: O(n)


Example#2: Factorial

Example#3: Tower of Hanoi puzzle

3 pegs (towers) and a stack of n disks having different diameters

Tower 1		Tower 2		Tower3

disk1
disk2
disk3


Objective: move all n disks from the tower 1 to tower 3 using tower 2 as a temporary storage place
while obeying the following rules: 

a. We are not allowed to place a large ring on a smaller one
b. We can move only one disk at a time

It takes 2^n - 1 steps to solve the puzzle

64 gloden rings among 3 towers of pure diamond ---> Bad news: World would end 
Good news: if they can move 1 disk every second of every day, it would take them 584 billion years
to complete the puzzle: 2^64 - 1 sec


TOH(n, start, end, extra):

if(n==0) return;

TOH(n-1, start, extra, end)
moveOneRing(start, end)
TOH(n-1, extra, end, start)

fib(3) = fib(2) + fib(1) = fib(1) + fib(0) + fib(1)

































